<template>
  <div>
    <el-card style="margin:20px 20px">
      <template #header>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="showAddDialog({id: 0, tmName: '',logoUrl:''})">添加</el-button>
      </template>
      <el-table
        v-loading="loading"
        :data="trademarkList"
        border
        style="width: 100%"
      >
        <el-table-column
          label="序号"
          width="80"
          type="index"
          align="center"
        />
        <el-table-column
          prop="tmName"
          label="品牌名称"
        />
        <el-table-column label="品牌LOGO" prop="logoUrl">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" style="width: 100px; height:60px;">
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button
              size="mini"
              icon="el-icon-edit-outline"
              title="修改"
              style="margin-right:10px"
              @click="showAddDialog(row)"
            />
            <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" icon="el-icon-info" icon-color="red" title="这是一段内容确定删除吗" @onConfirm="deleteTrademark(row)">
              <el-button slot="reference" icon="el-icon-delete" type="danger" size="small" title="删除" />
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next, jumper,-> ,sizes,total"
        :total="total"
        :page-sizes="[3, 5, 7, 9]"
        :page-size="limit"
        :current-page.sync="page"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog :visible.sync="dialogFormVisible" :title="`${this.formData.id ? '修改' : '添加'}品牌`" :before-close="handleClose">
      <el-form ref="addTrademarkRef" :rules="formRules" :model="formData" style="width: 80%">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="formData.tmName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseURL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg文件，且不能超过2M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdateTm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getAllTrademarkListApi, addTradeMarkApi, updateTradeMarkApi, remove } from '@/api/product/trademark'
export default {
  name: 'Trademark',
  data() {
    return {
      page: 1,
      limit: 5,
      total: 0,
      trademarkList: [],
      dialogFormVisible: false,
      loading: false,
      formEl: '',
      formData: {
        id: 0,
        tmName: '',
        logoUrl: ''
      },
      formRules: {
        tmName: [
          { required: true, message: '品牌名称必须填写', trigger: 'blur' },
          { min: 2, max: 10, message: '品牌长度未2-10', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '品牌LOGO必须上传', trigger: 'change' }
        ]
      },
      baseURL: '/dev-api'
    }
  },
  mounted() {
    this.getTrademarkList()
  },
  methods: {
    async getTrademarkList() {
      try {
        this.loading = true
        const res = await getAllTrademarkListApi(this.page, this.limit)
        this.trademarkList = res.data.records
        console.log(res.data.total)
        this.total = res.data.total
        this.loading = false
      } catch (error) {
        console.log(error)
        // ElMessage.error('获取品牌列表失败')
      }
    },
    // 每页条数变化执行的回调
    handleSizeChange(num) {
      // 默认新参可以接收到最新的每页条数
      this.limit = num
      this.getTrademarkList()
    },
    // 当前页变化执行的回调
    handleCurrentChange(num) {
      // 新参默认接收最新页码
      this.page = num
      this.getTrademarkList()
    },
    handleClose(done) {
      done()
    },
    handleAvatarSuccess(res, file) {
      this.formData.logoUrl = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image.jpg'
      const isLt2M = file.size / 1024 / 1024 > 2
      if (!isJPG) {
        this.$message.error('上传品牌图片只能是 JPG或JPEG 格式')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2M')
      }
      return isJPG && isLt2M
    },
    // 点击添加显示对话框
    async showAddDialog(row) {
      this.formData.tmName = row.tmName
      this.formData.logoUrl = row.logoUrl
      this.formData.id = row.id
      this.$refs.addTrademarkRef?.clearValidate()
      // 显示对话框
      this.dialogFormVisible = true
    },
    // 添加或者修改品牌的请求逻辑
    async addOrUpdateTm() {
      const { id } = this.formData
      if (id) {
        await updateTradeMarkApi(this.formData)
      } else {
        await addTradeMarkApi(this.formData)
      }
      this.dialogFormVisible = false
      this.$message.success(`${id ? '修改' : '添加'}品牌成功`)
      this.getTrademarkList()
    },
    async deleteTrademark(tm) {
      await remove(tm.id)
      this.$message.success('删除品牌成功')
      this.getTrademarkList()
    }

  }
}
</script>

<style scoped>
  .add-trademark {
  margin-bottom: 10px;
}
.trademark-img {
  height: 60px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  border: 1px dashed #d9d9d9;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
